package com.cet.algorithm.哈希表;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: algorithm
 * @description: 赎金信
 * @author: 陈恩涛
 * @create: 2022-03-12 20:49
 **/
public class LC383 {

    /**
     * 异位词解法
     * @param ransomNote
     * @param magazine
     * @return
     */
    public static boolean canConstruct(String ransomNote, String magazine) {
        int[] alphabetCounter = new int[26];
        for (int i = 0; i < magazine.length(); i++) {
            alphabetCounter[magazine.charAt(i) - 'a']++;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            alphabetCounter[ransomNote.charAt(i) - 'a']--;
        }
        for (int i : alphabetCounter) {
            if (i < 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * hash表解法
     * @param ransomNote
     * @param magazine
     * @return
     */
    public static boolean canConstruct2(String ransomNote, String magazine) {

        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < magazine.length(); i++) {
            map.merge(magazine.charAt(i), 1, Integer::sum);
        }

        for (int i = 0; i < ransomNote.length(); i++) {
            if (map.get(ransomNote.charAt(i)) == null || map.get(ransomNote.charAt(i)) == 0) {
                return false;
            }
            map.merge(ransomNote.charAt(i), -1, Integer::sum);
        }
        return true;
    }
}
